package cc.rengu.igas.smps.core.packswitch;

import cc.rengu.igas.smps.common.constant.SmpsParamConstant;
import cc.rengu.igas.smps.common.enums.RespCodeEnum;
import cc.rengu.jradp.packetswitch.IncomingPackSwitchImpl;
import cc.rengu.jradp.packetswitch.OutgoingPackSwitchImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.realize.SysParamService;
import cc.rengu.oltp.service.realize.impl.SysParamServiceImpl;
import cc.rengu.oltp.utility.util.MD5Util;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;

import java.util.Map;

/**
 * 与意锐服务商音箱通讯
 *
 * @author WKF
 */
public class SunyardVoiceClientPackSwitch implements IncomingPackSwitchImpl, OutgoingPackSwitchImpl {

    @Override
    public int beforeOutgoPackSwitch() throws Exception {

        return 0;
    }

    @Override
    public byte[] afterOutgoPackSwitch(byte[] arg0) throws Exception {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        String jsonBefore = new String(arg0);
        /* 生成签名 */
        String sign = generateSignBlockString(jsonBefore);
        if (null == sign) {
            rglog.error("生成加签Block失败!");
            throw new BizException(RespCodeEnum.GENERATE_SIGN_BLOCK_ERROR.getRespCode(), RespCodeEnum.GENERATE_SIGN_BLOCK_ERROR.getRespDesc());
        }
        rglog.debug("签名:<{}>", sign);
        /**添加sign字符串到报文中*/
        String jsonAfter = jsonStringAppendSign(jsonBefore, sign);

        return jsonAfter.getBytes();
    }


    @Override
    public int afterInComPackSwitch() {

        return 0;
    }

    @Override
    public byte[] beforeInComPackSwitch(byte[] arg0) throws Exception {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        //不验签了
        return arg0;
    }

    private String generateSignBlockString(String jsonString) {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        try {
            if (null != jsonString && 0 != jsonString.trim().length()) {
                //TODO：需配置参数表信息
                JSONObject jsonObject = JSONObject.parseObject(jsonString, Feature.OrderedField);
                String paramType = SmpsParamConstant.VOICE_SIGNTYPE_PREFIX;
                String paramKey = SmpsParamConstant.VOICE_SIGNKEY_PREFIX;
                SysParamService sysParamService = new SysParamServiceImpl();
                SysParam sysParam = sysParamService.getSysParamInfo(AppParamConstant.DEFAULT_INSTID, paramType, paramKey);
                String neededSign = "";
                if (null != sysParam) {
                    neededSign = sysParam.getParamValue();
                    StringBuffer strBuffer = new StringBuffer();
                    String[] signData = neededSign.split(",");
                    if (signData != null && signData.length != 0) {
                        for (int i = 0; i < signData.length - 1; i++) {
                            if (jsonObject.getString(signData[i]) != null) {
                                strBuffer.append(signData[i] + "=" + jsonObject.getString(signData[i]) + "&");
                            }
                        }
                        return MD5Util.MD5Encode(strBuffer.substring(0, strBuffer.length() - 1).toString()).toUpperCase();
                    }

                }
            }
        } catch (Exception e) {
            rglog.error("生成sign签名失败");
            rglog.error("系统异常!");
            return null;
        }
        return null;
    }

    private String jsonStringAppendSign(String jsonString, String sign) {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        try {
            if (null != jsonString && 0 != jsonString.trim().length()) {
                Map maps = (Map) JSON.parse(jsonString);
                maps.put("sign", sign);
                return JSON.toJSONString(maps);
            }
        } catch (Exception e) {
            rglog.error("添加sign签名失败");
            rglog.error("系统异常!");
            return null;
        }
        return null;
    }


}
